<?php
namespace app\admin\controller\v1;
use app\admin\Adminbase;
use app\common\model\Freight as FreightModel;


class Freight extends Adminbase
{
	
	/**
	* 获取运费模板
	* /admin/v1/freight/xmlFreight
	* 需要登录 
	* @is_need_login true
	* @method post
	*/
	public function xmlFreight($shop_id='',$id=0){
		$request =  request();
		$shop_id = $shop_id ?: $request->userInfo['shop_id'];
		try {
			$model = model('freight');
			$model = $model->where("shop_id",$shop_id ?: 0);
			$model = $model->whereor("id",$id);
			$model = $model->field("name as label,id as value");
			$data = $model->select()->toArray();
			array_unshift($data,["label"=>"默认模板","value"=>""]);    
			return $request->isAjax() ? $this->ReSucess($data) : $data;	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}


     /**
     * 编辑/新增
     * /admin/v1/freight/edit
     * 需要登录
     * @is_need_login true
     * @method post
     */
     public function edit($freight_id,$shop_id,$is_def_freight,$data_cost){

         $request =  request();
         $param = $request ->post();
         $data_cost = json_decode($data_cost,true);

         $cost = array_unique(array_column($data_cost, 'province'));
         if(count($cost) != count($data_cost)){
             return $this->ReError("可配送区域重复，请检查！");
         }


        try {

             if($is_def_freight==1){
                 model('freight')->where('shop_id',$shop_id)->update(['is_default'=>0]);
                 model('freight')->where(['shop_id'=>$shop_id,'id'=>$freight_id])->update(['is_default'=>1]);
             }

                //计费方式(配送区域及运费)
                model('freight_cost')->where('freight_id',$freight_id)->delete();
                model('freight_cost')
                    ->allowField(['freight_id','province','first_num','freight','continued_num','renew'])
                    ->saveAll($data_cost);


            return $this->ReSucess();
        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }

    }

    /**
     * 获取所有商品下是否存在运费模板
     * /admin/v1/freight/getfreight
     * 需要登录
     * @is_need_login true
     * @method post
     */
    public function getfreight($freight_id){

        try {
                $result_freight=model('goods')->where('freight_id',$freight_id)->count();

                if($result_freight){
                    return $this->ReError('已有商品引用该模板，不能删除！');
                }

                //删除运费模板下的所属的区域
               model('freight_cost')->where(['freight_id'=>$freight_id])->delete();


            return $this->ReSucess();
        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }

    }

    public function delFreightCost($freight_id){

    }










}



